using System;
using System.Collections.Generic;
using System.Text;
using WindowsLive.Writer.Api;
using System.Windows.Forms;

namespace RelatedPostPlugin
{
    [WriterPlugin("1646C104-DC7A-4fc7-AD94-4D31585A118E", "Smart Link Inserter",
        ImagePath="Images.hyperlink.png",
        PublisherUrl="http://blogbydmt.blogspot.com",
        Description="Smarty link insertion plugin")]
    [InsertableContentSource("Link to a web page")]
    public class RelatedPostPlugin : ContentSource
    {
        public override DialogResult CreateContent(IWin32Window dialogOwner, ref string newContent)
        {
            using (InsertForm insertForm = new InsertForm())
            {
                string clipUrl = string.Empty;
                if (Clipboard.ContainsText())
                {
                    clipUrl = Clipboard.GetText();
                    if (!InsertForm.IsUrl(clipUrl) && !InsertForm.IsEmail(clipUrl))
                        clipUrl = string.Empty;
                }
                insertForm.SetItems(clipUrl, string.Empty, string.Empty);

                DialogResult result = insertForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    newContent = GetContent(insertForm.Params);
                }
                return result;
            }
        }

        private string GetContent(List<string> Params)
        {
            if (Params[0] == string.Empty || Params[1] == string.Empty) return string.Empty;
            if (!InsertForm.IsUrl(Params[0]) && !InsertForm.IsEmail(Params[0]))
            {
                MessageBox.Show("The entered Url is not valid", "Error", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return string.Empty;
            }
            string linkFormat = @"<a title=""{0}"" href=""{1}"">{2}</a>";
            string htmlCode = string.Format(linkFormat, Params[2], Params[0], Params[1]);
            return htmlCode;
        } 
    }
}
